//
//  PywSelectCouponController.m
//  PywSdk
//
//  Created by liangyidong on 16/3/5.
//  Copyright © 2016年 zero. All rights reserved.
//

#import "PywSelectCouponController.h"
#import "PywCoupon.h"
#import "PywSelectCouponCell.h"
#import "PywMasonry.h"
#import "PywCouponListApi.h"
#import "PywMBProgressHUD+Pyw.h"
#import "PywMJRefresh.h"

@interface PywSelectCouponController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic,strong) UITableView *mainTable;
@property (nonatomic,strong) UIView *headView;
@property (nonatomic,strong) UIView *footView;
@property (nonatomic,strong) UILabel *amountLabel;

@property (nonatomic,assign) CGFloat orgPayAmount;
@property (nonatomic,assign) CGFloat selectPayAmount;
@property (nonatomic,strong) NSMutableArray *allCoupons;
@property (nonatomic,strong) PywCouponListApi *couponListApi;

@property (nonatomic,strong) NSMutableArray *selectCoupons;

@property (nonatomic,assign) NSInteger page;

@property (nonatomic,strong) UILabel *promptLabel;
@property (nonatomic,strong) UILabel *selectPrompt;

@end

@implementation PywSelectCouponController

- (instancetype)initWithAmount:(CGFloat)amount
{
    self = [super init];
    if (self) {
        self.orgPayAmount = amount;
        self.selectPayAmount = 0;
    }
    return self;
}
#pragma mark -  setUp

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setUp];
}

- (void)setUp
{
    self.title = @"选择代金券";
    self.navigationItem.rightBarButtonItem = nil;
    
    self.page = 1;
    _allCoupons = [[NSMutableArray alloc] init];
    _selectCoupons = [[NSMutableArray alloc] init];
    [self.view addSubview:self.mainTable];
    [self.view addSubview:self.footView];
    [self.view addSubview:self.promptLabel];
    [self addContrins];
    
    [self requestCouponList];
}

- (void)addContrins
{
    [self.mainTable mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    WEAK_SELF;
    [self.footView mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.bottom.equalTo(weakSelf.view.mas_bottom);
        make.height.mas_equalTo(60);
        make.left.mas_equalTo(weakSelf.view.mas_left);
        make.right.mas_equalTo(weakSelf.view.mas_right);
    }];
    
    [self.promptLabel mas_makeConstraints:^(PywMASConstraintMaker *make) {
        make.centerX.equalTo(weakSelf.view.mas_centerX);
        make.centerY.equalTo(weakSelf.view.mas_centerY);
    }];
}

#pragma mark - getter

- (PywCouponListApi *)couponListApi
{
    if (!_couponListApi) {
        _couponListApi = [PywCouponListApi manager];
    }
    return _couponListApi;
}

- (UITableView *)mainTable
{
    if (!_mainTable) {
        _mainTable = [[UITableView alloc] initWithFrame:CGRectZero
                                                  style:UITableViewStyleGrouped];
        _mainTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _mainTable.delegate = self;
        _mainTable.dataSource = self;
        _mainTable.tableHeaderView = self.headView;
        _mainTable.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _mainTable.bounds.size.width, 60)];
        WEAK_SELF;
        _mainTable.mj_header = [PywMJRefreshNormalHeader headerWithRefreshingBlock:^{
            weakSelf.page = 1;
            [weakSelf requestCouponList];
        }];
        _mainTable.mj_footer = [PywMJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            weakSelf.page ++;
            [weakSelf requestCouponList];
        }];
    }
    return _mainTable;
}

- (UIView *)headView
{
    if (!_headView) {
        _headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.mainTable.bounds.size.width, 110)];
        
        UIView *backView = [[UIView alloc] initWithFrame:CGRectMake(0, 10, _headView.bounds.size.width, 60)];
        backView.backgroundColor = [UIColor whiteColor];
        [_headView addSubview:backView];
        
        WEAK_SELF;
        [backView mas_makeConstraints:^(PywMASConstraintMaker *make) {
            make.left.equalTo(_headView.mas_left);
            make.right.equalTo(_headView.mas_right);
            make.height.mas_equalTo(60);
            make.top.equalTo(_headView.mas_top).offset(10);
        }];
        
        UILabel *orderNameLabel = [[UILabel alloc] initWithFrame:CGRectMake(10, 0, 100.f, backView.bounds.size.height)];
        orderNameLabel.font = [UIFont systemFontOfSize:15];
        orderNameLabel.textColor = UIColorFromRGB(0xABAFBA);
        orderNameLabel.textAlignment = NSTextAlignmentCenter;
        orderNameLabel.numberOfLines = 2;
        NSString *orderName = @"订单金额：\n已选金额：";
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:orderName];
        NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
        [style setLineSpacing:6];
        style.alignment = NSTextAlignmentCenter;
        [attributedString addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, orderName.length)];
        orderNameLabel.attributedText = attributedString;
        [backView addSubview:orderNameLabel];
        [backView addSubview:self.amountLabel];
        
        [orderNameLabel mas_makeConstraints:^(PywMASConstraintMaker *make) {
            make.left.equalTo(backView.mas_left).offset(5);
            make.centerY.equalTo(backView.mas_centerY);
            make.width.mas_equalTo(100.f);
            make.height.equalTo(backView.mas_height);
        }];
        
        [self.amountLabel mas_makeConstraints:^(PywMASConstraintMaker *make) {
            make.right.equalTo(backView.mas_right).offset(-10);
            make.centerY.equalTo(backView.mas_centerY);
            make.width.mas_equalTo(140.f);
            make.height.equalTo(backView.mas_height);
        }];
        
        
        
        UILabel *promtLabel = [UILabel new];
        promtLabel.text = @"请选择要使用的代金券";
        promtLabel.font = [UIFont systemFontOfSize:15.f];
        [_headView addSubview:promtLabel];
        self.selectPrompt = promtLabel;
        
        [promtLabel mas_makeConstraints:^(PywMASConstraintMaker *make) {
            make.top.equalTo(backView.mas_bottom).offset(5);
            make.left.equalTo(backView.mas_left).offset(10);
            make.right.equalTo(backView.mas_right).offset(-10);
            make.height.mas_equalTo(30);
        }];
    }
    return _headView;
}

- (UIView *)footView
{
    if (!_footView) {
        _footView = [UIView new];
        UIButton *selectButton = [UIButton buttonWithType:UIButtonTypeCustom];
        selectButton.center = _footView.center;
        selectButton.layer.cornerRadius = 40/2;
        selectButton.layer.masksToBounds = YES;
        selectButton.layer.borderColor = UIColorFromRGB(0xD5D5D5).CGColor;
        selectButton.layer.borderWidth = .5f;
        selectButton.backgroundColor = [UIColor whiteColor];
        [selectButton setTitleColor:[UIColor blueColor]
                           forState:UIControlStateHighlighted];
        [selectButton setTitleColor:[UIColor blackColor]
                           forState:UIControlStateNormal];
        [selectButton setTitle:@"使用代金券"
                      forState:UIControlStateNormal];
        [selectButton addTarget:self
                         action:@selector(handleSelectCoupon:)
               forControlEvents:UIControlEventTouchUpInside];
        [_footView addSubview:selectButton];
        
        [selectButton mas_makeConstraints:^(PywMASConstraintMaker *make) {
            make.center.mas_equalTo(_footView.center);
            make.width.mas_equalTo(200);
            make.height.mas_equalTo(40);
        }];
        
        
    }
    return _footView;
}

- (UILabel *)amountLabel
{
    if (!_amountLabel) {
        _amountLabel = [UILabel new];
        _amountLabel.font = [UIFont systemFontOfSize:15];
        _amountLabel.textColor = UIColorFromRGB(0xABAFBA);
        _amountLabel.textAlignment = NSTextAlignmentRight;
        _amountLabel.numberOfLines = 2;
        [self updateMoneyAmount];
    }
    return _amountLabel;
}

- (UILabel *)promptLabel
{
    if (!_promptLabel) {
        _promptLabel = [UILabel new];
        _promptLabel.font = [UIFont systemFontOfSize:15.f];
        _promptLabel.text = @"没有可用代金券";
        _promptLabel.hidden = YES;
        _promptLabel.textColor = [UIColor grayColor];
    }
    return _promptLabel;
}

#pragma mark - Request

- (void)requestCouponList
{
    [PywMBProgressHUD showMessage:@"正在加载代金券..." toView:self.view];
    WEAK_SELF;
    [self.couponListApi getCouponListWithStatus:2 page:self.page success:^(NSString *status, id anyObjct) {
        STRONG_SELF(weakSelf);
        [strongSelf.mainTable.mj_header endRefreshing];
        [strongSelf.mainTable.mj_footer endRefreshing];
        [PywMBProgressHUD hideHUDForView:weakSelf.view];
        NSDictionary *orderDict = (NSDictionary *)anyObjct;
        NSInteger ack = [[orderDict objectForKey:@"ack"] integerValue];
        if (ack == 200) {
            NSArray *list = [[orderDict objectForKey:@"data"] objectForKey:@"list"];
            NSArray *coupons = [PywCoupon arrayOfModelsFromDictionaries:list error:nil];
            if (strongSelf.page == 1) {
                [strongSelf.allCoupons setArray:coupons];
            }else {
                [strongSelf.allCoupons addObjectsFromArray:coupons];
            }
            [strongSelf.mainTable reloadData];
            
            NSInteger total_pages = [[[orderDict objectForKey:@"data"] objectForKey:@"total_pages"] integerValue];
            if (strongSelf.page >= total_pages) {
                [strongSelf.mainTable.mj_footer setHidden:YES];
            }else {
                [strongSelf.mainTable.mj_footer setHidden:NO];
            }
        }
        [strongSelf hideShowPromptLabel];
    } fail:^(NSError *error) {
        [PywMBProgressHUD hideHUDForView:weakSelf.view];
        [PywMBProgressHUD showError:@"获取代金券失败"];
        [weakSelf hideShowPromptLabel];
    }];
}

#pragma mark - Action
/**
 *  更新选择金额
 */
- (void)updateMoneyAmount
{
    NSString *amount = [NSString stringWithFormat:@"￥%.2f\n￥ %.2f",self.orgPayAmount,self.selectPayAmount];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:amount];
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    [style setLineSpacing:6];
    style.alignment = NSTextAlignmentRight;
    [attributedString addAttribute:NSParagraphStyleAttributeName
                             value:style
                             range:NSMakeRange(0, amount.length)];
    
    NSString *keyText = [NSString stringWithFormat:@"￥ %.2f",self.selectPayAmount];
    NSRange range = [amount rangeOfString:keyText];
    if (range.length != NSNotFound) {
        [attributedString addAttribute:NSForegroundColorAttributeName
                                 value:[UIColor orangeColor]
                                 range:range];
    }
    _amountLabel.attributedText = attributedString;
}

/**
 *  选择代金券
 *
 *  @param sender <#sender description#>
 */
- (void)handleSelectCoupon:(UIButton *)sender
{
    if (self.getAmountBlock) {
        self.getAmountBlock(self.selectCoupons);
    }
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 *  隐藏显示没有数据提示
 */
- (void)hideShowPromptLabel
{
    self.promptLabel.hidden = YES;
    self.footView.hidden = NO;
    self.selectPrompt.hidden = NO;
    
    if (self.allCoupons.count == 0) {
        self.promptLabel.hidden = NO;
        self.footView.hidden = YES;
        self.selectPrompt.hidden = YES;
    }
}


#pragma mark - TableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.allCoupons.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 60.f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 10.f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0.01f;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifiter = @"Cell";
    PywSelectCouponCell *cell = [tableView dequeueReusableCellWithIdentifier:identifiter];
    if (cell == nil) {
        cell = [[PywSelectCouponCell alloc] initWithStyle:UITableViewCellStyleDefault
                                          reuseIdentifier:identifiter];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        WEAK_SELF;
        cell.chooseCoupon = ^(NSInteger chooseAmount) {
            weakSelf.selectPayAmount += chooseAmount;
            BOOL isEnable = weakSelf.selectPayAmount >= weakSelf.orgPayAmount?NO:YES;
            for (PywCoupon *coupon in self.allCoupons) {
                coupon.isEnableChoose = isEnable;
            }
            [weakSelf.mainTable reloadData];
        };
    }
    PywCoupon *coupon = [self.allCoupons objectAtIndex:indexPath.section];
    cell.coupon = coupon;
    cell.orgPayAmount = self.orgPayAmount;
    cell.selectPayAmount = self.selectPayAmount;
    return cell;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    __block NSInteger amount = 0;
    PywCoupon *coupon = [self.allCoupons objectAtIndex:indexPath.section];
    if (!coupon.isChoose) {
        [self.allCoupons enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            PywCoupon *coupon = (PywCoupon *)obj;
            if (coupon.isChoose) {
                amount += coupon.chioceAmount;
            }
        }];
        if (amount >= self.orgPayAmount) {
//            [PywMBProgressHUD showError:@"已超过需要支付的金额"];
            return;
        }
    }
    
    coupon.isChoose = !coupon.isChoose;
    PywSelectCouponCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.selectPayAmount = self.selectPayAmount;
    [cell updateChooseStatus:coupon.isChoose];
    [self updateMoneyAmount];
    if ([self.selectCoupons containsObject:coupon]) {
        [self.selectCoupons removeObject:coupon];
    }else {
        [self.selectCoupons addObject:coupon];
    }
}


- (void)dealloc
{
    
}

@end
